package com.formen.ndk;
import java.io.*;
import java.sql.*;
import java.util.*;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity {
	String upLoadServerUri = null;
	Button loginBt;
	Button joinBt;
	EditText et1;
	EditText et2;
	public static String user_id;
	public static String user_pwd;
	public static String user_name;
	public static String user_birth;
	public static String user_number;
	public static String user_status;
	public static String user_location;
	public static Bitmap imgBitmap = null;
	public static ArrayList<Bitmap> bitArr = new ArrayList<Bitmap>();
	String filePath;
	int serverResponseCode = 0;
	public static boolean checker = false;
	public static ProgressDialog pDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		filePath = Environment.getExternalStorageDirectory()
				+ "/E-Profile";
		File dir = new File(filePath);
		dir.mkdir();
		loginBt = (Button) findViewById(R.id.main_login);
		joinBt = (Button) findViewById(R.id.user_join);
		et1 = (EditText) findViewById(R.id.user_id);
		et2 = (EditText) findViewById(R.id.user_pw);
		
		
		
		loginBt.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (et1.getText().toString().equals("")
						|| et2.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"ID or Password is Empty. Plz check it!",
							Toast.LENGTH_SHORT).show();
				} else {
					/*
					 * Intent intent = new
					 * Intent(MainActivity.this,Main1.class);
					 * startActivity(intent);
					 */
					BackThread backt1 = new BackThread();
					pDialog = ProgressDialog.show(MainActivity.this, "",
							"Now Loading...");
					backt1.setDaemon(true);
					backt1.start();
				}
			}
		});
		loginBt.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					loginBt.setBackgroundColor(Color.parseColor("#AA3333"));
					break;
				case MotionEvent.ACTION_UP:
					loginBt.setBackgroundColor(Color.TRANSPARENT);
					break;
				}
				return false;
			}
		});
		// 회원가입 join
		joinBt.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						Singin.class);
				startActivityForResult(intent, 0);
			}
		});
		joinBt.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					joinBt.setBackgroundColor(Color.parseColor("#AA3333"));
					break;
				case MotionEvent.ACTION_UP:
					joinBt.setBackgroundColor(Color.TRANSPARENT);
					break;
				}
				return false;
			}
		});
		
		
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			user_id = data.getStringExtra("Id");
			user_pwd = data.getStringExtra("Pwd");
			user_name = data.getStringExtra("Name");
			user_birth = data.getStringExtra("Birth");
			user_number = data.getStringExtra("Phone");
			user_status = data.getStringExtra("Status");
			user_location = data.getStringExtra("Location");
			
			SignIn();
			
		}
	}
	class BackThread extends Thread {
		public void run() {
			try {
				Class.forName("com.mysql.jdbc.Driver");
				Connection conn = null;
				Statement stmt = null;
				ResultSet rs = null;
				try {
					String jdbcDriver = "jdbc:mysql://sce.sejong.ac.kr:3306/firebat?"
							+ "useUnicode=true&characterEncoding=utf8";
					String dbUser = "firebat";
					String dbPass = "a1852411";
					// String query = "select * from CAPSTONE order by user_id";
					String query = "select * from  nfc_user where user_id= '"
							+ et1.getText().toString() + "' and user_pass='"
							+ et2.getText().toString() + "'";
					// 2.
					conn = DriverManager.getConnection(jdbcDriver, dbUser,
							dbPass);
					// 3.
					stmt = conn.createStatement();
					// 4.
					rs = stmt.executeQuery(query);
					// stmt.executeUpdate(query);
					// 5.
					if (rs.next()) {
						user_id = et1.getText().toString();
						user_name = rs.getString("name");
						user_number = rs.getString("mobile_number");
						user_location = rs.getString("location");
						user_birth = rs.getString("birth");
						user_status = rs.getString("status_msg");
					} else {
						pDialog.dismiss();
					}
					
					mHandler.post(new Runnable() {
						public void run() {
							if (pDialog.isShowing()) {
								pDialog.dismiss();
								Toast.makeText(getApplicationContext(),
										user_name + " Welcome Bro :D",
										Toast.LENGTH_SHORT).show();
								Intent intent = new Intent(MainActivity.this,
										Main1.class);
								startActivity(intent);
								finish();
							} else {
								Toast.makeText(
										getApplicationContext(),
										"Sry. Check ID/Pass or join E-Profile :p",
										Toast.LENGTH_SHORT).show();
							}
						}
					});
				} catch (SQLException ex) {
					pDialog.dismiss();
					ex.printStackTrace();
				} finally {
					// 6.
					if (rs != null)
						try {
							rs.close();
						} catch (SQLException ex) {
						}
					if (stmt != null)
						try {
							stmt.close();
						} catch (SQLException ex) {
						}
					// 7.
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException ex) {
						}
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} // run
	} //
	Handler mHandler = new Handler();
	int check = 0;
	long backtime;
	public boolean onKeyDown(int key, KeyEvent event) {
		if ((key == KeyEvent.KEYCODE_BACK)) {
			long currentTime = System.currentTimeMillis();
			final int duration = 2000;
			check++;
			if (check == 1) {
				backtime = System.currentTimeMillis();
				Toast t = Toast.makeText(getBaseContext(),
						"끌라고? 끌라믄 한번 더 누르던가...", Toast.LENGTH_SHORT);
				t.setDuration(duration);
				t.show();
				new Thread(new Runnable() {
					public void run() {
						try {
							Thread.sleep(duration);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						check = 0;
					}
				}).start();
			} else if (check == 2) {
				if (currentTime - backtime <= duration) {
					// return super.onKeyDown(key, event);
					android.os.Process.killProcess(android.os.Process.myPid());
				}
				check = 0;
			}
			return true;
		}
		return super.onKeyDown(key, event);
	}
	public void SignIn() {
		SignThread sgn1 = new SignThread();
		pDialog = ProgressDialog.show(MainActivity.this, "",
				"등록중...");
		sgn1.setDaemon(true);
		sgn1.start();
	}
	class SignThread extends Thread {
		public void run() {
			try {
				Class.forName("com.mysql.jdbc.Driver");
				Connection conn = null;
				Statement stmt = null;
				ResultSet rs = null;
				String query = "";
				try {
					String jdbcDriver = "jdbc:mysql://sce.sejong.ac.kr:3306/firebat?"
							+ "useUnicode=true&characterEncoding=utf8";
					String dbUser = "firebat";
					String dbPass = "a1852411";
					// String query = "select * from CAPSTONE order by user_id";
					
					// 2.
					conn = DriverManager.getConnection(jdbcDriver, dbUser,
							dbPass);
					// 3.
					stmt = conn.createStatement();
					
					
					// 4.
					query = "insert into nfc_user values ('" + user_id + "', '"
							+ user_name + "', '" + user_number + "', '"
							+ user_location + "', '" + user_birth + "', '"
							+ user_pwd + "', '" + user_status + "' )";
					
					
					stmt.executeUpdate(query);
					
					
					// 5.
				} catch (SQLException ex) {
					Log.d("Query", ex.toString());
					pDialog.dismiss();
					
					this.interrupt();
					ex.printStackTrace();
					
				} finally {
					mHandler.post(new Runnable() {
						public void run() {
							if (pDialog.isShowing()) {
								checker = true;
								Toast.makeText(getApplicationContext(),
										user_name + "Connecter에 오신걸 환영해요",
										Toast.LENGTH_SHORT).show();
								et1.setText(user_id);
								et2.setText(user_pwd);
								pDialog.dismiss();

							} else {
								Toast.makeText(
										getApplicationContext(),
										"ID가 중복인가봐요. 다시 해봐요.",
										Toast.LENGTH_SHORT).show();
							}
						}
					});
					// 6.
					if (rs != null)
						try {
							rs.close();
						} catch (SQLException ex) {
						}
					if (stmt != null)
						try {
							stmt.close();
						} catch (SQLException ex) {
						}
					// 7.
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException ex) {
						}
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} // run
	} //
	
}